package vworld.business.world;

import generated.business.world.WorldServicePOA;
import generated.callback.ClientCallback;
import generated.domain.avatar.Avatar;
import generated.domain.room.Position;
import generated.domain.room.Room;
import generated.domain.user.User;
import generated.domain.world.Matrix;
import generated.domain.world.World;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.omg.CORBA.ORB;

import vworld.ServerSingleton;

public class WorldServiceServant extends WorldServicePOA {

	private ORB orb;

	public void setOrb(ORB pOrb) {
		orb = pOrb;
	}

	/* Utils */
	private boolean northGateAvailable(int abs) {
		return (abs != 0);
	}

	private boolean southGateAvailable(int abs, int lastRowAbs) {
		return (abs != lastRowAbs - 1);
	}

	private boolean eastGateAvailable(int ord, int lastColOrd) {
		return (ord != lastColOrd - 1);
	}

	private boolean westGateAvailable(int ord) {
		return (ord != 0);
	}

	public World createWorld(String name, Matrix size) {
		World newWorld = new World();
		newWorld.setName(name);
		newWorld.setSize(size);

		Room[] worldRooms = new Room[size.rowNumber * size.columnNumber];
		int roomNumber = 0;
		for (int rows = 0; rows < size.rowNumber; rows++) {
			for (int columns = 0; columns < size.columnNumber; columns++) {
				Room room = new Room(name + " Room " + "[" + rows + ","
						+ columns + "]", new Position(rows, columns),
						northGateAvailable(rows), southGateAvailable(rows,
								size.rowNumber), eastGateAvailable(columns,
								size.columnNumber), westGateAvailable(columns),
						new Avatar[0]);
				worldRooms[roomNumber] = room;
				roomNumber++;
			}
		}
		newWorld.setRooms(worldRooms);
		newWorld.setConnectedUsers(new User[0]);

		ServerSingleton.getInstance().WORLD_DAO.createWorld(newWorld);
		return newWorld;
	}

	public User[] getConnectedUsers() {
		List<User> connectedUsersList = new ArrayList<User>();
		for (Map.Entry<String, ClientCallback> e : ServerSingleton
				.getInstance().REGISTERED_CLIENT_MAP.entrySet()) {
			connectedUsersList.add(ServerSingleton.getInstance().userImpl
					.getUserByLogin(e.getKey()));
		}
		return connectedUsersList.toArray(new User[connectedUsersList.size()]);
	}

	public World getWorldByName(String name) {
		return ServerSingleton.getInstance().WORLD_DAO.getWorld(name);
	}

	public World[] getWorlds() {
		return ServerSingleton.getInstance().WORLD_DAO.getWorlds();
	}
}
